#################################################################################
# Copyright (c) 2018-2021, Texas Instruments Incorporated - http://www.ti.com
# All Rights Reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
#   list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
#   this list of conditions and the following disclaimer in the documentation
#   and/or other materials provided with the distribution.
#
# * Neither the name of the copyright holder nor the names of its
#   contributors may be used to endorse or promote products derived from
#   this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#################################################################################

import torch

###################################################
class PropagateQuantTensor(object):
    QUANTIZED_THROUGH_ESTIMATION = 0
    STRAIGHT_THROUGH_ESTIMATION = 1
    NO_QUANTIZATION_ESTIMATION = 2

    def __init__(self, func, quant_estimation_type, copy_always=True):
        self.func = func
        self.quant_estimation_type = quant_estimation_type
        self.copy_always = copy_always

    def __call__(self, x, *args, **kwargs):
        if self.func is not None:
            y = self.func(x, *args, **kwargs)
        else:
            y = args[0]
        #
        if self.quant_estimation_type == self.QUANTIZED_THROUGH_ESTIMATION:
            # backprop will flow through the backward function
            # as the quantized tensor is forwarded as it is.
            return y
        elif self.quant_estimation_type == self.STRAIGHT_THROUGH_ESTIMATION:
            # forward the quantized data, but in the container x_copy
            # here a copy of x is made so that the original is not altered (x is a reference in Python).
            # the backward will directly flow though x_copy and to x instead of going through y
            # copy_always can be set to False avoid this copy if possible.
            x_copy = x.clone() if self.copy_always or isinstance(x, torch.nn.Parameter) else x
            x_copy.data = y.data
            return x_copy
        elif self.quant_estimation_type == self.NO_QUANTIZATION_ESTIMATION:
            # beware! no quantization performed in this case.
            return x
        else:
            assert False, f'unknown quant_estimation_type {self.quant_estimation_type}'


class PropagateQuantTensorQTE(PropagateQuantTensor):
    def __init__(self, func):
        # QUANTIZED_THROUGH_ESTIMATION: backprop will flow through
        # the backward functions wrapped in this class
        super().__init__(func, quant_estimation_type=PropagateQuantTensor.QUANTIZED_THROUGH_ESTIMATION)


class PropagateQuantTensorSTE(PropagateQuantTensor):
    def __init__(self, func):
        # STRAIGHT_THROUGH_ESTIMATION: backprop will NOT flow through
        # the backward functions wrapped in this class
        super().__init__(func, quant_estimation_type=PropagateQuantTensor.STRAIGHT_THROUGH_ESTIMATION)

